import React, { useState, useEffect } from "react";
import { Modal, Button, Radio, Space, Tabs, Toast, Tag } from "antd-mobile";
import { CloseOutline } from "antd-mobile-icons";
import styles from "./index.module.less";
import { findNodeByBFS, findNodeByDFS } from "@/utils/treeSearch";
import { parse } from "uuid";

const { getChatModelList, postChatModelSelect } = $globalServicer("chat");

const ModelSelector = ({
  visible,
  onClose,
  modelId,
  onModelChange,
  chatId,
  type
}) => {
  const [activeTab, setActiveTab] = useState(null);
  const [selectedModel, setSelectedModel] = useState(modelId);
  const [modelList, setModelList] = useState([]);
  // State to track if the initial setting has been done after list load
  const [initialStateSet, setInitialStateSet] = useState(false);
  const billingModeMap = {
    1: '固定消耗',
    2: '最低消耗'
  }
  // 当外部 modelId 变化时，更新内部选中状态
  // useEffect(() => {
  //   // setSelectedModel(modelId);
  //   // 这里需要加一个广度优先查找，返回选择的tab和modelId
  //   //
  //   if (modelList.length && modelId) {
  //     const { node, parent } = findNodeByBFS(modelList, modelId, "moulds");
  //     if (parent) {
  //       setActiveTab(parent.name);
  //     }
  //     if (node) {
  //       setSelectedModel(node.id);
  //     }
  //   }
  // }, [modelId, modelList]);
  useEffect(() => {
    // Run only if the list is populated AND the initial state hasn't been set yet for this opening
    if (visible && modelList.length > 0 && !initialStateSet) {
      let initialTab = null;
      let initialModel = null;

      if (modelId) {
        // --- Scenario 1: modelId is provided ---
        const result = findNodeByDFS(modelList, modelId);
        console.log('===> result', result)
        if (result && result.node && result.parent) {
          // Found the model and its parent category
          initialTab = result.parent.name;
          initialModel = result.node.id;
        } else {
          // Provided modelId not found, fall back to default (first available)
          console.warn(
            `Provided modelId "${modelId}" not found in modelList. Falling back to default.`,
          );
          const firstCategory = modelList[0];
          if (firstCategory?.moulds?.length > 0) {
            initialTab = firstCategory.name;
            initialModel = firstCategory.moulds[0].id;
          }
        }
      } else {
        // --- Scenario 2: modelId is NOT provided ---
        // Default to the first model in the first category
        const firstCategory = modelList[0];
        if (firstCategory?.moulds?.length > 0) {
          initialTab = firstCategory.name;
          initialModel = firstCategory.moulds[0].id;
        }
      }

      // Set the determined initial state
      setActiveTab(initialTab);
      setSelectedModel(initialModel);
      // Mark that the initial state has been set for this modal instance
      setInitialStateSet(true);
    }
    // This effect specifically handles the *initial* setup after the list loads.
    // It depends on the list being populated and the visible state.
    // The `initialStateSet` flag prevents it from re-running unnecessarily if `modelList`
    // were to somehow change again while the modal is open.
  }, [modelList, visible, modelId, initialStateSet]); // Depend on list, visibility, the input modelId, and the flag
  // 获取模型列表
  useEffect(() => {
    if (visible) {
      setInitialStateSet(false);
      getChatModelList().then((res) => {
        setModelList(res);
      });
    }
  }, [visible]);

  const handleModelSelect = (value) => {
    setSelectedModel(value);
  };

  const handleConfirm = async () => {
    if (!selectedModel) {
      Toast.show({
        content: "请选择一个模型",
        type: "error",
      });
      return;
    }

    try {
      // 调用选择模型的接口
      await postChatModelSelect({
        mould_id: selectedModel,
        chat_id: chatId,
      });

      // 更新父组件的模型ID
      onModelChange(selectedModel);
      onClose();
      Toast.show({
        content: "模型选择成功",
        type: "success",
      });
    } catch (error) {
      console.log(error, 'error')
    }
  };

  const lineStatus = (status) => {
    switch (status) {
      case 1:
        return <Tag color='success'>正常</Tag>;
      case 2:
        return <Tag color='warning'>繁忙</Tag>;
      case 3:
        return <Tag color='danger'>拥挤</Tag>;
      default:
        return null;
    }
  }

  return (
    <Modal
      visible={visible}
      onClose={onClose}
      className={styles.customModalWrapper}
      content={
        <div className={styles.customModal}>
          <div className={styles.modalHeader}>
            <span className={styles.title}>选择模型</span>
            <Button
              className={styles.closeButton}
              fill="none"
              onClick={onClose}
            >
              <CloseOutline fontSize={24} />
            </Button>
          </div>
          <div className={styles.modalContent}>
            <Tabs activeKey={activeTab} onChange={setActiveTab}>
              {modelList.map((modelItemList) => (
                <Tabs.Tab title={modelItemList.name} key={modelItemList.name}>
                  <div className={styles.model_list}>
                    <p className={styles.model_list_desc}>
                      {modelItemList.description}
                    </p>
                    {
                      type == 3 ? (
                        <Radio.Group
                          value={selectedModel}
                          onChange={handleModelSelect}
                        >
                          <Space direction="vertical" block>
                            {modelItemList.moulds.map((model) => (
                              <Radio
                                key={model.id}
                                value={model.id}
                                block
                                disabled={model.is_advanced_card_enabled !== 1}
                                className={styles.model_item + (model.is_advanced_card_enabled !== 1 ? ` ${styles.card_enabled}` : "")}
                              >
                                <div className={styles.model_info}>
                                  <div className={styles.model_name}>
                                    <p>{model.name}</p>
                                    {lineStatus(model.status)}
                                  </div>
                                  <div className={styles.model_desc}>
                                    {billingModeMap[model.billing_mode]}
                                    {
                                      model.billing_mode == 1 ? model.fixed_diamond_cost : model.min_diamond_cost
                                    } 梦钥/次
                                  </div>
                                </div>
                              </Radio>
                            ))}
                          </Space>
                        </Radio.Group>
                      ) : (
                        <Radio.Group
                          value={selectedModel}
                          onChange={handleModelSelect}
                        >
                          <Space direction="vertical" block>
                            {modelItemList.moulds.map((model) => (
                              <Radio
                                key={model.id}
                                value={model.id}
                                block
                                className={styles.model_item}
                              >
                                <div className={styles.model_info}>
                                  <div className={styles.model_name}>
                                    <p>{model.name}</p>
                                    {lineStatus(model.status)}
                                  </div>
                                  <div className={styles.model_desc}>
                                    {billingModeMap[model.billing_mode]}
                                    {
                                      model.billing_mode == 1 ? model.fixed_diamond_cost : model.min_diamond_cost
                                    } 梦钥/次
                                  </div>
                                </div>
                              </Radio>
                            ))}
                          </Space>
                        </Radio.Group>
                      )
                    }
                  </div>
                </Tabs.Tab>
              ))}

              {/* <Tabs.Tab title="成长陪伴" key="enhanced">
                <div className={styles.model_list}>
                  <p className={styles.model_list_desc}>
                    全感官沉浸剧情互动，解锁不同故事路线，与AI角色深度飙戏，每一句话都改变剧情走向。此模式初次消耗梦钥为固定值，随着聊天记录的增加梦钥消耗小幅度增加。通过强制透支ai使用效果，在聊天过程中施加的指令均全局生效，在对话中使ai拥有连贯的最大记忆力。对话过程中可以随时切换对话模式和Ai模型。
                  </p>
                  <Radio.Group
                    value={selectedModel}
                    onChange={handleModelSelect}
                  >
                    <Space direction="vertical" block>
                      {modelList.enhanced.map((model) => (
                        <Radio
                          key={model.id}
                          value={model.id}
                          block
                          className={styles.model_item}
                        >
                          <div className={styles.model_info}>
                            <div className={styles.model_name}>
                              {model.name}
                            </div>
                            <div className={styles.model_desc}>
                              最低消耗 {model.min_diamond_cost} 梦钥
                            </div>
                          </div>
                        </Radio>
                      ))}
                    </Space>
                  </Radio.Group>
                </div>
              </Tabs.Tab> */}
            </Tabs>
          </div>
          <div className={styles.modalFooter}>
            <Button
              className={styles.cancelButton}
              fill="none"
              onClick={onClose}
            >
              取消
            </Button>
            <Button
              className={styles.confirmButton}
              color="primary"
              onClick={handleConfirm}
            >
              确认
            </Button>
          </div>
        </div>
      }
    />
  );
};

export default ModelSelector;
